﻿using AiChiTu.TraceabilitySystem.Domain.AiChiTuManagement;
using AiChiTu.TraceabilitySystem.ErrorCode;
using AiChiTu.TraceabilitySystem.ErrorCode.Extensions;
using AiChiTu.TraceabilitySystem.Infrastructure.Interfaces;
using AiChiTu.TraceabilitySystem.Write.API.Applications.Commands.ProductBasices;
using AutoMapper;
using MediatR;

namespace AiChiTu.TraceabilitySystem.Write.API.Applications.CommandsHandlers.ProductBasices
{
	public class UpdateProductBasicsCommandHandle : IRequestHandler<UpdateProductBasicsCommand, APIResult<bool>>
	{
		private readonly IBaseRepository<ProductBasics> productbasicRepository;
		private readonly IMapper mapper;

		public UpdateProductBasicsCommandHandle(IBaseRepository<ProductBasics> productbasicRepository, IMapper mapper)
		{
			this.productbasicRepository = productbasicRepository;
			this.mapper = mapper;
		}
		/// <summary>
		/// 修改商品基础信息请求命令处理
		/// </summary>
		/// <param name="request">修改商品基础信息请求命令</param>
		/// <param name="cancellationToken">取消</param>
		/// <returns>返回任务</returns>
		public async Task<APIResult<bool>> Handle(UpdateProductBasicsCommand request, CancellationToken cancellationToken)
		{
			APIResult<bool> result = new APIResult<bool>();
			result.Code = ResultCode.UpdateFailed;
			result.Message = ResultCode.UpdateFailed.GetDescription();
			result.Data = false;

			ProductBasics? productBasics = productbasicRepository.QueryEntityAsync(x => x.ProductBasicsId == request.ProductBasicsId).Result;
			productBasics = mapper.Map(request, productBasics);
			productBasics.UpdatePerson = request.CurrentLoginPerson;
			productBasics.UpdateTime = DateTime.Now;
			if (await productbasicRepository.UpdateEntityAsync(productBasics))
			{
				result.Code = ResultCode.UpdateSuccess;
				result.Message = ResultCode.UpdateSuccess.GetDescription();
				result.Data = true;
			}

			return await Task.FromResult(result);
		}
	}
}
